package com.pansoft.openplanet.activity.child;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.FileDeleteUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.model.ActGeneratorBean;
import com.pansoft.openplanet.account.model.BlockChainAccountInfoBean;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.account.util.ActAccountGenerator;
import com.pansoft.openplanet.account.util.EosAccountGenerator;
import com.pansoft.openplanet.account.util.EthAccountGenerator;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 使用私钥恢复
 */
public class ChildRestoreByPrivateKeyFragment extends BaseFragment {
    private View rootView;

    private EditText etPrivatekey;
    private Button butEnter;
    private String keyStoreDir;
    private static final String TAG = "ChildRestoreByPrivateKeyFragment";
    private BigInteger privateKey;
    private AccountDao accountDao;
    private String number;
    private String avatar;
    private String walletAvatar;//钱包账户头像
    private String walletName;//钱包账户名称
    private int chainId;//钱包类型
    private TCAccountManager tcAccountManager;
    //    private EditText etEosAccountName;
    private EditText etEosOwnerPrikey;
    private EditText etEosActivePrikey;

    private String ethPublicKey;
    private String ethAddress;
    List<String> accountNameList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.talk_chain_fragment_retorechild_byprivatekey, null);
        initView();
        initData();

        return rootView;
    }

    private void initData() {

        number = getActivity().getIntent().getExtras().getString("number");
        //userName = getActivity().getIntent().getExtras().getString("userName");
        avatar = getActivity().getIntent().getStringExtra("avatar");
        walletAvatar = getActivity().getIntent().getStringExtra("wallet_avatar");
        walletName = getActivity().getIntent().getStringExtra("wallet_name");
        chainId = getActivity().getIntent().getIntExtra("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);
        //创建目录
        keyStoreDir = TalkChainConstant.getChildAccountFilePath(getActivity()) + File.separator + EnvironmentVariable.getUserName();
        File file = new File(keyStoreDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (chainId == EosNetParamUtil.getEosChainId()) {
            etPrivatekey.setVisibility(View.GONE);
//            etEosAccountName.setVisibility(View.VISIBLE);
            etEosOwnerPrikey.setVisibility(View.VISIBLE);
            etEosActivePrikey.setVisibility(View.VISIBLE);

        }
        accountDao = new AccountDao(getActivity());
        tcAccountManager = new TCAccountManager(getActivity());
    }

    private void initView() {
        etPrivatekey = rootView.findViewById(R.id.et_privatekey);
        butEnter = rootView.findViewById(R.id.but_enter);
//        etEosAccountName = (EditText) rootView.findViewById(R.id.et_eos_account_name);
        etEosOwnerPrikey = (EditText) rootView.findViewById(R.id.et_eos_owner_prikey);
        etEosActivePrikey = (EditText) rootView.findViewById(R.id.et_eos_active_prikey);

        butEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = etPrivatekey.getText().toString().trim();
                if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                    if (TextUtils.isEmpty(key)) {
                        ToastUtils.showShort(R.string.open_planet_private_key_not_null);
                        return;
                    }
                    restoreEthByPrivateKey(IPAssetsConstant.ChainEnum.ETH);
                } else if (chainId == IPAssetsConstant.CHAIN_ID_ETE) {
                    if (TextUtils.isEmpty(key)) {
                        ToastUtils.showShort(R.string.open_planet_private_key_not_null);
                        return;
                    }
                    restoreEthByPrivateKey(IPAssetsConstant.ChainEnum.ETE);
                } else if (chainId == EosNetParamUtil.getEosChainId()) {
                    restoreEosByPrivateKey();
                } else if (chainId == IPAssetsConstant.CHAIN_ID_ACT) {
                    restorActByPrivateKey();
                }
            }
        });
    }


    /**
     * 通过私钥恢复Eos账户
     */
    private void restoreEosByPrivateKey() {
//        final String accountName = etEosAccountName.getText().toString().trim();
        String ownPrivateKey = etEosOwnerPrikey.getText().toString().trim();
        String activePrivateKey = etEosActivePrikey.getText().toString().trim();
        if (TextUtils.isEmpty(ownPrivateKey) || TextUtils.isEmpty(activePrivateKey)) {
            ToastUtils.showShort(R.string.open_planet_private_key_not_null);
            return;
        }

        Disposable disposable = EosAccountGenerator
                .getObservableByPrivateKey(ownPrivateKey, activePrivateKey)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        TCLoadingDataView.show(getActivity(), ResStringUtil
                                .getString(R.string.open_planet_checking_info));
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Map>() {
                    @Override
                    public void accept(Map map) throws Exception {
                        final Account account = new Account();
                        account.setAcccountName(walletName);
                        account.setAccountAvatar(walletAvatar);
                        account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                        account.setPublicKey((String) map.get("ownPubKey"));
                        account.setSecretPrivateKey((String) map.get("secretOwnPriKey"));
                        account.setEosActivePubKey((String) map.get("activePubKey"));
                        account.setEosActivePriKey((String) map.get("secretActivePriKey"));
                        account.setBlockChainName(EosNetParamUtil.getEosChainName());
                        account.setMaster(false);
                        account.setCurrentShow(false);
                        account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));

//                        todo test根据公钥调用接口查询地址
                        HashMap<String, String> hashMap = new HashMap<String, String>();
//                        hashMap.put("name", accountName);
//                        hashMap.put("accountName", accountName);
                        hashMap.put("ownerPublicKey", account.getPublicKey());
                        hashMap.put("activePublicKey", account.getEosActivePubKey());
                        hashMap.put("chainId", chainId + "");
                        //http://tc.solarsource.cn:9692/tcserver/eos/getAccount?accountName=eosio
                        TCRequestUtil.getCommonRequest(TAG, "eos/getKeyAccountsByKey", hashMap,
                                new TCRequestUtil.TCRequestCallback() {
                                    @Override
                                    public void onSuccess(String response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            if (jsonObject.optString("result").equals("success")) {
                                                JSONArray dataArray = jsonObject.optJSONObject("data").optJSONArray("account_names");
                                                for (int i = 0; i < dataArray.length(); i++) {
                                                    String accountName = dataArray.optString(i);
                                                    accountNameList.add(accountName);
                                                }
                                                account.setAddress(accountNameList.get(0));
                                                StringBuilder stringBuilder = new StringBuilder();
                                                for (String account : accountNameList) {
                                                    stringBuilder.append(account).append("_");
                                                }
                                                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                                                String eosAccountNames = stringBuilder.toString();
                                                account.setEosAccountNames(eosAccountNames);
                                                account.setActivate(true);

//                                        JSONObject dataObj = jsonObject.optJSONObject("data");
//                                        JSONArray keyArray = dataObj.optJSONArray("eosAccountKey");
//                                        String activeKey="";
//                                        String ownerKey="";
//                                        for (int i = 0; i < keyArray.length(); i++) {
//                                            JSONObject keyObject = keyArray.optJSONObject(i);
//                                            if (keyObject.optString("keyName").equals("owner")) {
//                                                ownerKey = keyObject.optString("key");
//                                            } else if (keyObject.optString("keyName").equals("active")) {
//                                                activeKey = keyObject.optString("key");
//                                            }
//                                        }
//                                        if (activeKey.equals(account.getEosActivePubKey()) && ownerKey.equals(account.getPublicKey())) {
//                                            //恢复成功，弹密码框，上传服务器，存本地
                                                showEosSuccessPassDialog(account);
//                                        }else {
//                                            TCLoadingDataView.dismiss();
//                                            ToastUtils.showShort(R.string.open_planet_recovering_fail_retry);
//                                        }
                                            } else {
                                                //未激活账号，弹密码框，上传服务器，存本地
                                                account.setActivate(false);
                                                account.setEosAccountNames("");
                                                account.setAddress(String.valueOf(TimeUtils.getNowMills()));
                                                showEosSuccessPassDialog(account);
//                                        TCLoadingDataView.dismiss();
//                                        ToastUtils.showShort(R.string.open_planet_recovering_fail_retry);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            TCLoadingDataView.dismiss();
                                            ToastUtils.showShort(R.string.open_planet_recovering_fail_retry);
                                        }
                                    }

                                    @Override
                                    public void onFail(String error) {
                                        TCLoadingDataView.dismiss();
                                        ToastUtils.showShort(R.string.open_planet_recovering_fail_retry);
                                    }
                                });
//                        HttpUtils.postRequest(BaseUrl.HTTP_get_chain_account_info, getActivity(), hashMap, new JsonCallback<ResponseBean<BlockChainAccountInfoBean.DataBean>>() {
//
//                            @Override
//                            public void onSuccess(Response<ResponseBean<BlockChainAccountInfoBean.DataBean>> response) {
//                                super.onSuccess(response);
//                                if (response.body().code == 0) {
//                                    dealResponse(response.body().data, account);
//                                } else {
//                                    ToastUtils.showShort("检查EOS地址公钥信息失败!");
//                                }
//                            }
//
//
//                        });


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        TCLoadingDataView.dismiss();
                        ToastUtils.showShort(R.string.open_planet_recovering_fail);

                    }
                });

        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    private void showEosSuccessPassDialog(final Account account) {
        PassWordAlertDialog dialog = new PassWordAlertDialog(getActivity(),
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
                        TCLoadingDataView.show(getActivity(), ResStringUtil
                                .getString(R.string.open_planet_importing));
                        TCAccountManager tcAccountManager = new TCAccountManager(getActivity());
                        tcAccountManager.addEosWallet(account, accountDao.getMainAccountInDb(), new TCAccountManager.AccountManagerListener() {
                            @Override
                            public void onSuccess(Object object) {
                                account.setEnable(true);
                                accountDao.insertOrReplace(account);
                                TCLoadingDataView.dismiss();
                                ToastUtils.showShort(R.string.open_planet_recovering_success);
                                ActivityCompat.finishAffinity(getActivity());
                            }

                            @Override
                            public void onFail(String fail) {
                                TCLoadingDataView.dismiss();
                                ToastUtils.showShort(R.string.open_planet_recovering_fail_retry);
                            }
                        });
                    }
                });
        dialog.setCanCancle(false);
        dialog.show();
    }

    private void showMainAccountNameSelect(Account account) {

    }

    private void dealResponse(BlockChainAccountInfoBean.DataBean blockChainAccountInfoBean, final Account account) {
        String chainAccountOwnerKey = null;
        String chainAccountActiveKey = null;
        for (int i = 0; i < blockChainAccountInfoBean.getPermissions().size(); i++) {
            if (blockChainAccountInfoBean.getPermissions().get(i).getPerm_name().equals("owner")) {
                chainAccountOwnerKey = blockChainAccountInfoBean.getPermissions().get(i).getRequired_auth().getKeys().get(0).getKey();
            } else {
                chainAccountActiveKey = blockChainAccountInfoBean.getPermissions().get(i).getRequired_auth().getKeys().get(0).getKey();
            }
        }
        if (account.getEosActivePubKey().equals(chainAccountActiveKey) && account.getPublicKey().equals(chainAccountOwnerKey)) {
            TCAccountManager manager = new TCAccountManager(getActivity());
            manager.addEosWallet(account, new AccountDao(getActivity()).getMainAccountInDb(), new TCAccountManager.AccountManagerListener() {
                @Override
                public void onSuccess(Object object) {

                }

                @Override
                public void onFail(String fail) {

                }
            });
            account.setEnable(true);
            accountDao.insertOrReplace(account);
            ToastUtils.showShort(R.string.open_planet_recovering_success);
            ActivityCompat.finishAffinity(getActivity());

        } else {
            ToastUtils.showShort(R.string.open_planet_conflict_account);
        }
    }

    /**
     * 通过私钥恢复ETH账户
     */
    private void restoreEthByPrivateKey(final IPAssetsConstant.ChainEnum blockChainEnum) {

        TCLoadingDataView.show(getActivity(), R.string.open_planet_recovering);
        if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
//            BTCWalletManager btcWalletManager = new BTCWalletManager(getActivity());
//            btcWalletManager.restoreWalletByPrivKey("L4zHDQoHtW96ghbsmaN3L6HJqN8B8kiUnjEf9XT5HPxNFTcJ6Tga",
//                    "", "比特4", new BTCWalletManager.BTCWalletRestoreListener() {
//                        @Override
//                        public void onRestoreSuccess(Account account) {
//
//                        }
//
//                        @Override
//                        public void onRestoreFail() {
//
//                        }
//                    });
//            return;
        }
        String key = etPrivatekey.getText().toString().trim();
        Disposable disposable = EthAccountGenerator.recoverAccountByPrivateKey(keyStoreDir, key, new EthAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(EthBean ethBean) {
                Account dbAccout = accountDao.getAccount(ethBean.getEthAddress());
                if (dbAccout != null && dbAccout.isEnable()) {
                    //if (accountDao.getAccount(ethBean.getEthAddress()) != null) {
                    TCLoadingDataView.dismiss();
                    showCoverAlertDialog();
                    FileDeleteUtil.delete(new File(ethBean.getKeyStoreFilePath()));
                    return;
                } else {
                    final Account account = new Account();
                    account.setAccountAvatar(walletAvatar);
                    account.setAddress(ethBean.getEthAddress());
                    account.setFileName(ethBean.getKeyStoreFilePath());
                    account.setAcccountName(walletName);
                    account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                    account.setBlockChainName(blockChainEnum.chainName);
                    account.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                    account.setMaster(false);
                    account.setCurrentShow(false);
                    account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                    //account.setEnable(true);
                    accountDao.insertOrReplace(account);

                    String publicKey = ethBean.getEcKeyPair().getPublicKey().toString();
                    String privateKey = ethBean.getEcKeyPair().getPrivateKey().toString();
                    //生成的账户放到服务器
                    tcAccountManager.addChildWallet(publicKey, privateKey, ethBean.getEthAddress(), walletAvatar, walletName
                            , account.getBlockChainName(), null, new TCAccountManager.AccountManagerListener<String>() {
                                @Override
                                public void onSuccess(String object) {
                                    TCLoadingDataView.dismiss();
                                    //恢复成功，更改状态为可用
                                    if (account != null) {
                                        account.setEnable(true);
                                        accountDao.insertOrReplace(account);
                                    }
                                    ToastUtils.showShort(R.string.open_planet_recovering_success);
                                    getActivity().finishAffinity();
                                }

                                @Override
                                public void onFail(String fail) {
                                    TCLoadingDataView.dismiss();
                                    showFailAlert(null);
                                }
                            });


                }
            }

            @Override
            public void generatorFail() {
                TCLoadingDataView.dismiss();
                showFailAlert(null);
            }
        });

        ((TCBaseActivity) getActivity()).addDisposable(disposable);

    }


    /**
     * 恢复 act钱包
     */
    private void restorActByPrivateKey() {
        final String key = etPrivatekey.getText().toString().trim();
        TCLoadingDataView.show(getActivity(), R.string.open_planet_recovering);
        Disposable disposable = ActAccountGenerator.recoverAccountByPrivateKey(key, new ActAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(ActGeneratorBean actGeneratorBean) {
                Account dbAccout = accountDao.getAccount(actGeneratorBean.getWalletAddress());
                if (dbAccout != null && dbAccout.isEnable()) {
                    //if (accountDao.getAccount(actGeneratorBean.getWalletAddress()) != null) {
                    //账户重复
                    TCLoadingDataView.dismiss();
                    showCoverAlertDialog();
                    return;
                }
                final Account account = new Account();
                account.setAccountAvatar(walletAvatar);
                account.setAddress(actGeneratorBean.getWalletAddress());
                account.setAcccountName(walletName);
                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                account.setPublicKey(actGeneratorBean.getPublicKey());
                account.setSecretPrivateKey(actGeneratorBean.getSecretPriKey());
                account.setMaster(false);
                account.setCurrentShow(false);
                account.setBlockChainName(IPAssetsConstant.ChainEnum.ACHAIN.chainName);
                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                //account.setEnable(true);
                accountDao.insertOrReplace(account);

                //生成的账户放到服务器
                tcAccountManager.addChildWallet(actGeneratorBean.getPublicKey(), key, actGeneratorBean.getWalletAddress(), walletAvatar, walletName
                        , IPAssetsConstant.ChainEnum.ACHAIN.chainName, null, new TCAccountManager.AccountManagerListener<String>() {
                            @Override
                            public void onSuccess(String object) {
                                TCLoadingDataView.dismiss();
                                //恢复成功，更改状态为可用
                                if (account != null) {
                                    account.setEnable(true);
                                    accountDao.insertOrReplace(account);
                                }
                                ToastUtils.showShort(R.string.open_planet_recovering_success);
                                getActivity().finishAffinity();
                            }

                            @Override
                            public void onFail(String fail) {
                                TCLoadingDataView.dismiss();
                                showFailAlert(null);
                            }
                        });
            }

            @Override
            public void generatorFail() {
                TCLoadingDataView.dismiss();
            }
        });
        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((TCBaseActivity) getActivity()).dispose();
    }

    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_recovering_fail_retry);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                })
                .create()
                .show();
    }

    /**
     * 提示具有重复账户
     */
    private void showCoverAlertDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.open_planet_import_wallet_exist))
                .setPositiveButton(R.string.common_text_confirm, null)
                .create()
                .show();
    }


}
